//
//  VCOfSearch.m
//  SeeTheWorld
//
//  Created by dllo on 16/2/29.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "VCOfSearch.h"
#import "PCH.pch"
#import "ItemOfLvXingDi.h"
#import "ItemOfYongHu.h"
#import "NetworkingHandler.h"
#import "ModelOfLvXingDi.h"
#import <AFNetworking.h>
#import "ModelOfYongHu.h"

#import "DataBaseHandler.h"
#import "ModelOfHistory.h"
#import "VCOfClickYongHu.h"
#import "VCOfClickLvXingDi.h"
#import "VCOfClickHistory.h"
#import <UIImageView+WebCache.h>


@interface VCOfSearch () <UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, ItemOfYongHuDelegate, ItemOfLvXingDiDelegate>

@property (nonatomic, retain)UIButton *buttonOfRight;
@property (nonatomic, retain)UISearchBar *search;
@property (nonatomic, retain)UISegmentedControl *segment;
@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, retain)NSMutableArray *arrayOfLvXingDi;
@property (nonatomic, retain)NSMutableArray *arrayOfYongHu;
@property (nonatomic, retain)NSString *text;

@property (nonatomic, retain)NSMutableArray *history;
@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain)UILabel *labelOfCleraHistory;
@property (nonatomic, retain)UIView *view1;

@property (nonatomic, retain)UIImageView *imageOfZhanWei;
@property (nonatomic, retain)UILabel *labelOfZhanWei;

@property (nonatomic, retain)NSArray *arrayOfReMen;

@end

@implementation VCOfSearch

- (void)dealloc {
    self.search.delegate = nil;
    self.collectionView.delegate = nil;
    self.collectionView.dataSource = nil;
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    [_arrayOfReMen release];
    [_imageOfZhanWei release];
    [_labelOfZhanWei release];
    [_view1 release];
    [_labelOfCleraHistory release];
    [_tableView release];
    [_history release];
    [_text release];
    [_arrayOfLvXingDi release];
    [_arrayOfYongHu release];
    [_collectionView release];
    [_flowLayout release];
    [_segment release];
    [_buttonOfRight release];
    [_search release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor colorWithRed:43 / 256.f green:115 / 256.f blue:217 / 256.f alpha:1], [UIColor colorWithRed:39 / 256.f green:39 / 256.f blue:39 / 256.f alpha:1]);
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.history = [[DataBaseHandler shareDataBaseHandler] history];
    
    self.search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 6 * 5, 28)];
    self.navigationItem.titleView = self.search;
    self.search.placeholder = @"请输入旅行地";
    self.search.delegate = self;
    [self.search release];
    
    self.navigationItem.hidesBackButton = YES;
    
    /** 主页navigation右侧button */
    self.buttonOfRight = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonOfRight.frame = CGRectMake(self.search.frame.size.width + 5, 10, 40, 40);
    [self.buttonOfRight addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonOfRight setTitle:@"取消" forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:self.buttonOfRight]autorelease];
    
    /** 创建tableView */
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"pool0"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"pool7"];
    
    self.arrayOfReMen = @[@"夏威夷", @"马尔代夫", @"北海道", @"泰国", @"海南", @"斯里兰卡", @"美国"];

}

/** 返回脚部<清除历史纪录> */
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if (self.history.count == 0) {
        
        return nil;
        
    } else {
        
        if (section == 0) {

        self.labelOfCleraHistory = [[UILabel alloc] init];
        self.labelOfCleraHistory.text = @"清除历史纪录";
        self.labelOfCleraHistory.textAlignment = NSTextAlignmentCenter;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clear:)];
        [self.labelOfCleraHistory addGestureRecognizer:tap];
        [tap release];
        self.labelOfCleraHistory.userInteractionEnabled = YES;
        self.labelOfCleraHistory.dk_textColorPicker = DKColorWithRGB(0x343434, 0xffffff);

        return self.labelOfCleraHistory;
            
        } else {
            
            return nil;
        }
    }
}

/** 清除历史纪录手势方法实现 */
- (void)clear:(UITapGestureRecognizer *)tap {
    
    [self.history removeAllObjects];
    [self.tableView reloadData];
    
    [[DataBaseHandler shareDataBaseHandler] deleteHistory];
    
}

/** 脚部高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 30;
}

//* 点击cell 
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.history.count == 0) {
        VCOfClickHistory *vc = [[VCOfClickHistory alloc] init];
        vc.text = [self.arrayOfReMen objectAtIndex:indexPath.row];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        if (indexPath.section == 0) {
            
            ModelOfHistory *model = [self.history objectAtIndex:indexPath.row];
            
            VCOfClickHistory *vc = [[VCOfClickHistory alloc] init];
            vc.text = model.text;
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            
            VCOfClickHistory *vc = [[VCOfClickHistory alloc] init];
            vc.text = [self.arrayOfReMen objectAtIndex:indexPath.row];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
        }
        
       
        
    }
    
}

/** 区头高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 30;
}

/** 区头标题 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if (self.history.count == 0) {
        
        return @"热门搜索";
        
    } else {
        
        if (section == 0) {
            return @"搜索历史";
        } else {
            
            return @"热门搜索";
        }
        
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.history.count == 0) {
        
        return 1;
        
    } else {
        
        return 2;
    }
}

/** cell高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

/** cell行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.history.count == 0) {
        
        return 7;
        
    } else {
        
        if (section == 0) {
            return self.history.count;
            
        } else {
            return 7;
        }
        
    }
    
}

/** 返回cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.history.count == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool7"];
        cell.textLabel.text = [self.arrayOfReMen objectAtIndex:indexPath.row];
        cell.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
        cell.textLabel.dk_textColorPicker = DKColorWithRGB(0x343434, 0xffffff);
        
        return cell;
        
    } else {
        
        if (indexPath.section == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool0"];
            
            ModelOfHistory *model = [self.history objectAtIndex:indexPath.row];
            
            cell.textLabel.text = model.text;
            cell.textLabel.dk_textColorPicker = DKColorWithRGB(0x343434, 0xffffff);
            cell.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
            return cell;
            
        } else {
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool7"];
            cell.textLabel.text = [self.arrayOfReMen objectAtIndex:indexPath.row];
            cell.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
            cell.textLabel.dk_textColorPicker = DKColorWithRGB(0x343434, 0xffffff);
            
            return cell;
            
        }
        
        
    }
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    [self.imageOfZhanWei removeFromSuperview];
    [self.labelOfZhanWei removeFromSuperview];
    
    [self.arrayOfLvXingDi removeAllObjects];
    [self.arrayOfYongHu removeAllObjects];
    
    [self.collectionView reloadData];
    
}

#pragma mark - 点击键盘搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    /** 判断是否重复加入数据库 */
    if ([[DataBaseHandler shareDataBaseHandler] selectForHistory:searchBar.text]) {
        
    } else {
        
        [[DataBaseHandler shareDataBaseHandler] insertModel1:searchBar.text];
    
    }
    
    /** 释放第一响应 */
    [self.search resignFirstResponder];
    
    self.text = searchBar.text;
    
    [self createSegmentedControl];
    
#pragma mark - 解析数据(旅行地)
    NSString *urlStr=[NSString stringWithFormat:@"http://chanyouji.com/api/search/attractions.json?page=1&q=%@", self.search.text];
    
    //转码，把汉字转为
    urlStr =[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            
            self.arrayOfLvXingDi = [NSMutableArray array];
            
            for (NSDictionary *dic in responseObject) {
                ModelOfLvXingDi *model = [[ModelOfLvXingDi alloc] init];
                model.text = searchBar.text;
                [model setValuesForKeysWithDictionary:dic];
                [self.arrayOfLvXingDi addObject:model];
                [model release];
            }
            
        
  }
        
        /** 判断数组是否为空<这里空荡荡> */
        if (self.arrayOfLvXingDi.count == 0) {
            
            self.imageOfZhanWei = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"KongDangDang"]];
            [[self.view viewWithTag:100] addSubview:self.imageOfZhanWei];
            self.imageOfZhanWei.frame = CGRectMake(WIDTH / 3, HEIGHT / 4 - 50, WIDTH / 3, WIDTH / 3);
            [_imageOfZhanWei release];
            
            self.labelOfZhanWei = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 3, HEIGHT / 4 - 50 + WIDTH / 3, WIDTH / 3, 40)];
            [[self.view viewWithTag:100] addSubview:self.labelOfZhanWei];
            self.labelOfZhanWei.text = @"这里空荡荡";
            self.labelOfZhanWei.textAlignment = 1;
            [_labelOfZhanWei release];
            self.labelOfZhanWei.dk_textColorPicker = DKColorWithRGB(0x343434, 0xffffff);
            self.labelOfZhanWei.font = [UIFont systemFontOfSize:20];
        }
        
        [self.collectionView reloadData];
        
        }
        
    ];
    
    [dataTask resume];
    
#pragma mark - 解析数据(用户)
    NSString *urlStr1=[NSString stringWithFormat:@"http://chanyouji.com/api/search/users.json?page=1&q=%@",self.search.text];
    
    //转码，把汉字转为
    urlStr1 =[urlStr1 stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURLSessionConfiguration *configuration1 = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager1 = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration1];
    
    NSURL *URL1 = [NSURL URLWithString:urlStr1];
    NSURLRequest *request1 = [NSURLRequest requestWithURL:URL1];
    
    NSURLSessionDataTask *dataTask1 = [manager1 dataTaskWithRequest:request1 completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            
            self.arrayOfYongHu = [NSMutableArray array];
            
            for (NSDictionary *dic in responseObject) {
                ModelOfYongHu *model = [[ModelOfYongHu alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                model.text = searchBar.text;
                [self.arrayOfYongHu addObject:model];
                [model release];
            }
            
        }

        [self.collectionView reloadData];
        
    }];
    
    [dataTask1 resume];
    
    /** 创建CollectionView */
    [self createCollectionView];
    
    /** KVO: 使UISegmentedControl 和 collectionView关联 */
    [self.collectionView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:@"context"];
    [self.segment addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];
     
}

/** 创建CollectionView */
- (void)createCollectionView {
    
    if (self.collectionView) {
        
        return;
    }
    
    /** 创建collectionView */
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 100);
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.flowLayout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, WIDTH, HEIGHT - 100) collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [_collectionView release];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.bounces = NO;
    [self.collectionView registerClass:[ItemOfLvXingDi class] forCellWithReuseIdentifier:@"pool"];
    [self.collectionView registerClass:[ItemOfYongHu class] forCellWithReuseIdentifier:@"pool1"];
    self.collectionView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    
    
}

- (void)createSegmentedControl {
    
    if (self.view1) {
        return;
    }
    
    /** 主页分段控制条 */
    self.view1 = [[UIView alloc] init];
    self.view1.backgroundColor = [UIColor whiteColor];
    self.view1.frame = CGRectMake(0, 64, WIDTH, 36);
    [self.view addSubview:self.view1];
    [self.view1 release];
    self.view1.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"旅行地", @"用户"]];
    self.segment.frame = CGRectMake(5, 2, WIDTH - 10, 32);
    [self.view1 addSubview:self.segment];
    self.segment.selectedSegmentIndex = 0;
    self.segment.backgroundColor = [UIColor colorWithRed:230 / 256.f green:230 / 256.f blue:230 / 256.f alpha:0.5];
    [_segment release];
    self.segment.dk_tintColorPicker = DKColorWithColors([UIColor lightGrayColor], [UIColor whiteColor]);
    
}

#pragma mark - KVO主页: SegmentedControl关联collectionView
- (void)action:(UISegmentedControl *)seg {
    
    [UIView animateWithDuration:0.5 animations:^{
        switch (seg.selectedSegmentIndex) {
            case 0:
            {
                self.collectionView.contentOffset = CGPointZero;
                break;
            }
            case 1:
            {
                self.collectionView.contentOffset = CGPointMake(WIDTH, 0);
            }
            default:
                break;
        }
    }];
    
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    if ([[change objectForKey:@"new"] CGPointValue].x == WIDTH) {
        
        self.segment.selectedSegmentIndex = 1;
        
    } else if ([[change objectForKey:@"new"] CGPointValue].y == 0) {
        
        self.segment.selectedSegmentIndex = 0;
    }
}

#pragma mark - collectionView协议方法
/** 返回Item个数 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}

/** 返回cell */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.item == 0) {
        
        ItemOfLvXingDi *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool" forIndexPath:indexPath];
        cell.tag = 100;
        cell.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
        cell.delegate = self;
        [cell passModel:self.arrayOfLvXingDi];
        
        return cell;
    }
    else  {
        
        ItemOfYongHu *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];
        cell.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
        cell.delegate = self;
        [cell passModel:self.arrayOfYongHu];
        
        return cell;
    }
    
}

- (void)passID:(NSString *)id {
    
    VCOfClickLvXingDi *vc = [[VCOfClickLvXingDi alloc] init];
    vc.id = id;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
   // self.hidesBottomBarWhenPushed = NO;
    [vc release];
    
}

- (void)passID:(NSString *)id name:(NSString *)name {
    
    VCOfClickYongHu *VC1 = [[VCOfClickYongHu alloc] init];
    
    VC1.id = id;
    VC1.name = name;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC1 animated:YES];
   // self.hidesBottomBarWhenPushed = NO;
    [VC1 release];
    
    
}

- (void)search:(UIButton *)button {
    [self.search resignFirstResponder];
    [self.segment removeFromSuperview];
    [self.collectionView removeFromSuperview];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
